package com.smartmail.utility;

import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import android.util.Log;

/**
 * Class used for handling inconsistent with RFC standards subject fields
 * in message headers.
 * 
 * @author Tomek
 *
 */
public class MimeMessageDecodeUtil {
	
	
	/**
	 * Set default charset.
	 * @param charset - default charset
	 */
	public static void setDefaultCharset(String charset){
		
		System.setProperty("mail.mime.charset", charset);
	}
	
	/**
	 * Get default charset.
	 * @return - default charset
	 */
	public static String getDefaultCharset(){
		
		return System.getProperty("mail.mime.charset");
	}
	
	/**
	 * Get Subject from message.
	 * 
	 * @param mimeMessage 
	 * @return - subject of given message
	 * @throws MessagingException
	 */
	public static String getSubject(MimeMessage mimeMessage) throws MessagingException{
		
		String subject = null;
		String rawSubject = mimeMessage.getHeader("Subject", null);
		
		if( rawSubject == null)
			return null;
		
		//Log.d(_logTag, "MimeMessageDecodeUtil : " + rawSubject);
		
		rawSubject = MimeUtility.unfold(rawSubject);
		
		try{
			
			if(rawSubject.indexOf("=?")==-1){
				
				subject = mimeMessage.getSubject();
				byte[] bts2 = new byte[subject.length()];
				for(int j=0;j<subject.length();j++){
					
					char c = subject.charAt(j);
					bts2[j] = (byte)c;		
				}
				return  new String(bts2, getDefaultCharset());
			}
			else
				return mimeMessage.getSubject();
		}catch(MessagingException me){
			
			throw new MessagingException("messaging exception", me);
			
		}catch(UnsupportedEncodingException uee){
			
			return null;
		}
	}
	
	/**
	 * logTag for logging purposes
	 */
	private static String _logTag = "com.smartmail.mime";

}
